package my.study.org.mongodb.examples;

import java.net.UnknownHostException;

import my.study.org.mongodb.constant.MongoDBConstant;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.common.base.Preconditions;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class InsertAddBatch {
	private final static Log logger = LogFactory.getLog(InsertAddBatch.class);

	/**
	 * @param args
	 * @throws MongoException
	 * @throws UnknownHostException
	 */
	public static void main(String[] args) throws UnknownHostException,
			MongoException {
		insertOneByOne(100000);
		insertAddBatch(100000);
	}

	public static void insertOneByOne(long size) throws UnknownHostException,
			MongoException {
		Mongo mongo = new Mongo(MongoDBConstant.MONGO_HOST,
				MongoDBConstant.MONGO_PORT);

		logger.info(mongo.getDatabaseNames());
		DB db = mongo.getDB(MongoDBConstant.MONGO_DB_NAME);
		db.dropDatabase();

		DBCollection coll = db.getCollection("collectionnoexist");

		logger.info(mongo.getDatabaseNames());
		logger.info("begin to insert");
		long beginTime = System.currentTimeMillis();
		for (int i = 0; i < size; i++) {
			DBObject doc = new BasicDBObject();
			doc.put("name", "fanhongjie" + i);
			doc.put("age", i);
			coll.insert(doc);
		}
		logger.info("end insert takes "
				+ (System.currentTimeMillis() - beginTime) + "ms");
		long expect = coll.getCount();
		Preconditions.checkState(expect == size, "insert fail " + expect + "!="
				+ size);
		logger.info(mongo.getDatabaseNames());
		coll.drop();
		db.dropDatabase();

		logger.info(mongo.getDatabaseNames());
	}

	public static void insertAddBatch(long size) throws UnknownHostException,
			MongoException {
		Mongo mongo = new Mongo(MongoDBConstant.MONGO_HOST,
				MongoDBConstant.MONGO_PORT);

		logger.info(mongo.getDatabaseNames());
		DB db = mongo.getDB("mydbnotexit");
		db.dropDatabase();

		DBCollection coll = db.getCollection("collectionnoexist");

		logger.info(mongo.getDatabaseNames());
		logger.info("begin to insert");
		long beginTime = System.currentTimeMillis();
		DBObject[] docs = new DBObject[(int) size];
		for (int i = 0; i < size; i++) {
			DBObject doc = new BasicDBObject();
			doc.put("name", "fanhongjie" + i);
			doc.put("age", i);
			docs[i] = doc;
		}
		logger.info("finish get data");
		coll.insert(docs);
		logger.info("end insert takes "
				+ (System.currentTimeMillis() - beginTime) + "ms");
		long expect = coll.getCount();
		Preconditions.checkState(expect == size, "insert fail " + expect + "!="
				+ size);
		logger.info(mongo.getDatabaseNames());
		//coll.drop();
		//db.dropDatabase();
		logger.info(coll.getCount());
		logger.info(mongo.getDatabaseNames());
	}

}
